﻿using Npgsql;
using NpgsqlTypes;
using System;
using System.Data;
using static Dapper.SqlMapper;
using BJoin.Common;
namespace BJoin.DapperExtension.Postgresql
{
    public class ArrayParameter : ICustomQueryParameter
    {
        private readonly object _value;

        public ArrayParameter(object value)
        {
            _value = value;
        }

        public void AddParameter(IDbCommand command, string name)
        {
            NpgsqlParameter param = new NpgsqlParameter(name, NpgsqlDbType.Array | NpgsqlDbType.Bigint)
            {
                Value = _value
            };
            param.ParameterName = name;
            if (_value.GetType().IsArrayOf<int>())
            {
                param.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Integer;
            }
            else if (_value.GetType().IsArrayOf<long>())
            {
                param.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Bigint;
            }
            else if (_value.GetType().IsArrayOf<string>())
            {
                param.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Varchar;
            }
            else if (_value.GetType().IsArrayOf<decimal>())
            {
                param.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Numeric;
            }
            else if (_value.GetType().IsArrayOf<double>())
            {
                param.NpgsqlDbType = NpgsqlDbType.Array | NpgsqlDbType.Double;
            }
            command.Parameters.Add(param);
        }
    }
}
